﻿#include "OperScript.h"
#include "FITK_Kernel/FITKAppFramework/FITKAppFramework.h"
#include "FITK_Kernel/FITKAppFramework/FITKAppScriptHelper.h"
#include "FITK_Kernel/FITKAppFramework/FITKAppSettings.h"
#include "FITK_Kernel/FITKAppFramework/FITKGlobalData.h"
#include <QWidget>
#include <QAction>
#include <QFileDialog>

bool GUIOper::OperScript::execGUI()
{
    //根据不同按钮执行不同操作
    if (_emitter == nullptr) return false;
    QString name = _emitter->objectName();
    //开始记录
    if (name == "actionRecordScript")
    {
        this->recordScript();
    }
    //结束记录
    else if (name == "actionEndScript")
    {
        this->endScript();
    }
    //执行脚本
    else if (name == "actionRunScript")
    {
        this->runScript();
    }

    return false;
}

void GUIOper::OperScript::recordScript()
{
    QWidget* mw = FITKAPP->getGlobalData()->getMainWindow();
    if (!mw) return;
    //记录脚本名与结束记录脚本按钮状态设置
    QAction* act = mw->findChild<QAction*>("actionRecordScript");
    if (act) act->setEnabled(false);
    act = mw->findChild<QAction*>("actionEndScript");
    if (act) act->setEnabled(true);
    //打开记录状态
    AppFrame::FITKAppScriptHelper* h = FITKAPP->getScriptHelper();
    if (h)
        h->enableRecord();

}

void GUIOper::OperScript::endScript()
{
    QWidget* mw = FITKAPP->getGlobalData()->getMainWindow();
    if (!mw) return;
    //关闭记录状态
    AppFrame::FITKAppScriptHelper* h = FITKAPP->getScriptHelper();
    if (!h) return;

    //获取工作目录
    QString wk;
    AppFrame::FITKAppSettings* settings = FITKAPP->getAppSettings();
    if (settings)
        wk = settings->getWorkingDir();
    //对话框选择文件
    QString fileName = QFileDialog::getSaveFileName(mw, tr("Save Script"), wk, tr("Py File(*.py)"));
    if (fileName.isEmpty())return;
    //写出文件
    h->exportScriptFile(fileName);

    //记录脚本名与结束记录脚本按钮状态设置
    QAction* act = mw->findChild<QAction*>("actionRecordScript");
    if (act) act->setEnabled(true);
    act = mw->findChild<QAction*>("actionEndScript");
    if (act) act->setEnabled(false);
    
    h->enableRecord(false);
  

}

void GUIOper::OperScript::runScript()
{
    QWidget* mw = FITKAPP->getGlobalData()->getMainWindow();
    if (!mw) return;
    //获取工作路径
    QString wk;
    AppFrame::FITKAppSettings* settings = FITKAPP->getAppSettings();
    if (settings)
        wk = settings->getWorkingDir();
    //获取文件路径与文件名
    QString fileName = QFileDialog::getOpenFileName(mw, tr("Run Script"), wk, tr("Py File(*.py)"));
    if (fileName.isEmpty())return;
    //执行脚本文件
    AppFrame::FITKAppScriptHelper* h = FITKAPP->getScriptHelper();
    if (h) h->execScriptFile(fileName);
}
